/**
 * 
 */
package com.feib.stms.dao.jdbc.rowmapper;

import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;

import org.springframework.jdbc.core.RowMapper;

import com.feib.stms.dao.MenuItemDao;
import com.feib.stms.model.MenuItem;
import com.feib.stms.util.SpringContextUtil;

/**
 * @author Jimmy Liu
 *
 */
public class MenuItemRowMapper extends BaseRowMapper<MenuItem> implements RowMapper<MenuItem>
{

	private static final long serialVersionUID = 8355941710618906106L;
	
	private MenuItemDao menuItemDao;
	
	private Map<Long, MenuItem> parentCaches = new HashMap<Long, MenuItem>();

	public MenuItemRowMapper() {
		super(MenuItem.class);
	}
	
	public MenuItemRowMapper(MenuItemDao menuItemDao)
	{
		super(MenuItem.class);
		this.menuItemDao = menuItemDao;
		
		if (null == this.menuItemDao )
		{
			menuItemDao = (MenuItemDao)SpringContextUtil.getBean("menuItemDao");
		}
	}
	
	@Override
	protected MenuItem doOtherMapRow(ResultSet rs, int rowNumber, MenuItem entity) 
	{
		entity.setEnabled(getColumnBoolean(rs, "IS_ENABLED"));
		entity.setSecurities(getColumnBoolean(rs, "IS_SECURITIES"));
		
		Long parentMenuItemPk = (Long)getColumnValue(rs, "PARENT_MENU_ITEM_PK", Long.class);
		if (null != parentMenuItemPk)
		{
			// 從 cache裡面抓取，節省與資料庫連結時間
			// 不同的Menu可能會有相同的 parentMenu
			MenuItem parentMenuItem = parentCaches.get(parentMenuItemPk);
			if (null == parentMenuItem)
			{
				parentMenuItem = menuItemDao.getByMenuItemPk(parentMenuItemPk);
				parentCaches.put(parentMenuItem.getMenuItemPk(), parentMenuItem);
			}
			
			entity.setParentMenuItem(parentMenuItem);
		}
		
		
		return entity;

	}
}
